<?php
/**
 * Created by PhpStorm.
 * User: chentairen
 * Date: 2017/11/16
 * Time: 上午10:49
 */

namespace App\Service;


use App\Model\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AdminService
{
    protected $error = '';

    /**
     * 后台用户登录
     */
    public function login($tel, $code, $remember, $passportService)
    {
        $admin = Admin::where('tel', $tel)->first();
        if (!$admin) {
            $this->error = '该账号不存在';
            return false;
        }
        if ($admin->status != 1) {
            $this->error = '该账号未激活';
            return false;
        }
        $re = $passportService->isCheckPhoneCode($tel, $code);
        if (!$re) {
            $this->error = '验证码错误';
            return false;
        }
        Auth::guard('admin')->login($admin, $remember);
        (new Admin())->cacheRules($admin->id);
        return true;

    }

    /**
     * 添加后台管理员
     * @param $data
     * @return array|bool
     */
    public function addAdmin($data)
    {
        $has = Admin::where('tel', $data['tel'])->count();
        if ($has > 0) {
            $this->error = '该手机号已存在';
            return false;
        }
        DB::beginTransaction();
        $admin = Admin::create($data);
        $re = $admin->roles()->sync($data['role_id']);
        if (!$admin || !$re) {
            $this->error = '添加失败';
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;

    }

    /**
     * 编辑管理员
     * @param $data
     * @return bool
     */
    public function editAdmin($data)
    {
        $id = Admin::where('tel', $data['tel'])->value('id');
        if ($id && $id != $data['id']) {
            $this->error = '该手机号已存在';
            return false;
        }
        $admin = Admin::find($data['id']);
        DB::beginTransaction();
        $admin->username = $data['username'];
        $admin->email = $data['email'];
        $admin->tel = $data['tel'];
        $re1 = $admin->save();
        $re2 = $admin->roles()->sync($data['role_id']);
        if (!$re1 || !$re2) {
            $this->error = '添加失败';
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public function getError()
    {
        return $this->error;
    }
}